<script setup lang="ts">
import { translate } from '@/service/translate'

const translateStore = useTranslate()

const loading = ref(false)

const start = () => {
  translateStore.result = ''

  const { eventSource, close, uid } = useSse()

  const over = () => {
    loading.value = false
    close()
  }

  loading.value = true

  eventSource.onopen = () => {
    translate.translate({
      apiKey: translateStore.apiKey,
      fromLanguage: translateStore.fromLanguage,
      toLanguage: translateStore.toLanguage,
      text: translateStore.text
    }, uid).catch((res: any) => {
      over()
      ElNotification({
        title: '系统错误',
        message: res?.response?._data?.error?.message || '未知异常',
        type: 'error'
      })
    }).then(({ code }:any) => {
      if (code && code !== 200) {
        over()
      }
    })
  }

  eventSource.onmessage = (e) => {
    if (e.data === '[DONE]') {
      over()
      return
    }
    try {
      const data = JSON.parse(e.data)
      if (data.content) {
        translateStore.result += data.content
      }
    } catch {
      over()
    }
  }

  eventSource.addEventListener('error', over)
}
</script>
<template>
  <div>
    <div class="text-2xl font-bold pl-3 pb-2">
      AI翻译
    </div>
    <!-- 选择器 -->
    <TranslateControl />
    <!-- 内容区域 -->
    <TranslateContent />
    <!-- 执行按钮 -->
    <div class="flex items-center justify-center">
      <el-button class="mx-auto text-2xl w-60 h-14" type="success" :loading="loading" @click="start">
        翻译
      </el-button>
    </div>
  </div>
</template>
